package com.pmgames.store.data
{
	import com.pmgames.store.data.ExtendedArrayCollection;
	
	import mx.controls.Alert;

	public class WordToGuess_Anagr
	{
		//private var unscrambledWord:WordItem;
		private var word:WordItem;
		
		public function WordToGuess_Anagr(source:RelationArrayCollection = null)
		{
			if(source != null)
			{
				word = RelationItem(source.getItemAt(source.length - 1)).sourceId;
				word.changedName = scrambleExpression(RelationItem(source.getItemAt(source.length - 1)).sourceId);
			}	
		}
		public function setWord(value:WordItem):void
		{
			word = value;
		}	
		
		public function getWord():WordItem
		{
			return word;
		}		
				
		
		public function scrambleWord(singleWord:String):String
		{
			var indexes:ExtendedArrayCollection = ExtendedArrayCollection.setIndexes(singleWord.length);
			var scrambledWord:String = "";
			for(var index:int = 0; index < indexes.length; index++)
			{
				scrambledWord += singleWord.charAt(parseInt(String(indexes.getItemAt(index))));
			}			
			return scrambledWord;
		}
		
		public function scrambleExpression(word:WordItem):String
		{
			var scrambledExpression:String = "";
			var unscrambledWord:String = word.name.toUpperCase();
			var singleWords:Array = unscrambledWord.split( /[^A-Z]+/ );
			var index:int = 0;
			var ind:int = 0;
			while( ind < unscrambledWord.length )
			{ 
				while(ind < unscrambledWord.length 
				&& (unscrambledWord.charAt(ind) < "A" 
					|| unscrambledWord.charAt(ind) > "Z"))
				{
					scrambledExpression += unscrambledWord.charAt(ind);
					ind++;
				} 		
				if(	index < singleWords.length)
				{		
					scrambledExpression += scrambleWord(singleWords[index]);
					index++;
				}
				while(ind < unscrambledWord.length 
				&& (unscrambledWord.charAt(ind) >= "A" 
					&& unscrambledWord.charAt(ind) <= "Z"))
				{
					ind++;
				}									
			} 
			return scrambledExpression;	
		}
			
	}
}